'use strict';

console.log('This server is only for develop and debug, DO NOT USE THIS FOR PRODUCTION.');

const express = require('express');
const httpProxy = require('http-proxy');

const port = 3000;
const app = express();
const proxy = httpProxy.createProxyServer({ target: 'http://localhost:8080' });

proxy.on('error', e => {
  console.log(e);
});

const defaultUser = {
  id: 1,
  email: 'a@terminus.io',
  nick: 'Anson',
  avatar: 'http://anson.so/img/avatar.png',
  roles: [
    { role: 'SYS_ADMIN' },
    { role: 'COMPANY_ADMIN', targetId: 1, displayName: '某公司' },
    { role: 'DEV_TEAM_LEADER', targetId: 1, displayName: '某开发组' }
  ]
};
let loginUser = defaultUser;

app.use(express.static('public'));

app.get('/api/users/current', (req, res) => {
  res.send(loginUser);
});

app.post('/api/users/login', (req, res) => {
  loginUser = defaultUser;
  res.send(loginUser);
});

app.post('/api/users/logout', (req, res) => {
  loginUser = undefined;
  res.send('');
});

app.get('/api/users/search', (req, res) => {
  res.send({
    list: [
      {
        id: 1,
        email: 'a@terminus.io',
        avatar: 'http://anson.so/img/avatar.png',
        nick: 'Anson',
        mobile: '18668143963',
        status: 'ACTIVE'
      }, {
        id: 2,
        email: 's@terminus.io',
        status: 'NEW'
      }, {
        id: 3,
        email: 'g@terminus.io',
        status: 'LOCK'
      }
    ],
    total: 120
  });
});

app.get('/api/roles/user/:userId/all', (req, res) => {
  res.send(loginUser.roles);
});

app.delete('/api/roles/:roleId', (req, res) => {
  res.send('');
});

app.post('/api/roles', (req, res) => {
  res.send('');
});

app.get('/api/users/current/dev-teams', (req, res) => {
  setTimeout(() => {
    res.send([
      { id: 1, name: '端点特别行动小组', logo: 'http://git.terminus.io/terminus/Beedrill/avatar' },
      { id: 2, name: 'TOT(Terminus Office Team)', logo: 'http://git.terminus.io/uploads/project/avatar/208/logo.png' }
    ]);
    // res.sendStatus(500);
  }, 1000);
});

app.get('/api/users/current/runnable-groups', (req, res) => {
  res.send([
    { id: 1, name: 'Pampas' },
    { id: 2, name: 'Neverest' }
  ]);
});

app.get('/api/dev-teams/:id/detail', (req, res) => {
  res.send({
    devTeam: {
      id: req.params.id,
      name: '端点特别行动小组',
      logo: 'http://git.terminus.io/terminus/Beedrill/avatar',
      desc: '只有精英存在的小队！'
    },
    members: [
      { id: 1, nick: 'Anson Chan', email: 'a@terminus.io', avatar: 'http://anson.so/img/avatar.png' },
      { id: 2, nick: 'Saito Wu', email: 's@terminus.io', avatar: 'https://avatars2.githubusercontent.com/u/348915?v=3&s=96' }
    ],
    runnableGroups: [
      { id: 1, name: 'Pampas' },
      { id: 2, name: 'Neverest', desc: '不息峰，永不休息的数据平台' }
    ]
  });
});

app.get('/api/runnable-groups/:id', (req, res) => {
  res.send({
    runnableGroup: {
      id: req.params.id,
      name: 'Neverest',
      desc: '不息峰，永不休息的数据平台'
    },
    runnableRuntimes: [
      { id: 1, name: '生产' },
      { id: 2, name: '测试' },
      { id: 3, name: '性能' }
    ]
  });
});

const units = [
  {
    id: 1,
    runtimeId: 1,
    name: 'Neverest-UI',
    type: 'LINNER',
    url: 'git@git.terminus.io/neverest/neverest-ui:master',
    lastBuild: {
      status: 'BUILDING',
      uuid: '3345-5432-123',
      createdAt: 1318781876406,
      updatedAt: 1318781876406
    },
    machines: [{ id: 1, ip: '10.0.0.1' }, { id: 2, ip: '10.0.0.2' }]
  }, {
    id: 2,
    runtimeId: 1,
    name: 'Neverest-Service',
    type: 'MAVEN',
    url: 'git@git.terminus.io/neverest/neverest-service:master',
    children: [
      { id: 3, runtimeId: 1, name: 'user', url: '/user', machines: [{ id: 1, ip: '10.0.0.1' }, { id: 2, ip: '10.0.0.2' }] },
      { id: 4, runtimeId: 1, name: 'monitor', url: '/monitor', machines: [{ id: 1, ip: '10.0.0.1' }, { id: 2, ip: '10.0.0.2' }] },
      { id: 5, runtimeId: 1, name: 'analyze', url: '/analyze', machines: [{ id: 1, ip: '10.0.0.1' }, { id: 2, ip: '10.0.0.2' }] }
    ]
  }, {
    id: 6,
    runtimeId: 1,
    name: 'Parana-User',
    type: 'DOCKER_IMAGE',
    url: 'terminus/parana-user:1.0',
    machines: [{ id: 1, ip: '10.0.0.1' }, { id: 2, ip: '10.0.0.2' }]
  }
];

app.get('/api/runnable-runtimes/:id/runnable-units', (req, res) => {
  res.send(units);
});

app.post('/api/runnable-runtimes', (req, res) => {
  setTimeout(() => {
    res.send({
      id: 10086,
      name: '来一发'
    });
  }, 1000);
});

app.delete('/api/runnable-runtimes/:runtimeId', (req, res) => {
  setTimeout(() => {
    res.send('');
  }, 1000);
});

app.get('/api/machines/search', (req, res) => {
  res.send({
    list: [
      { id: 1, sourceId: 1, ip: '192.168.0.1', name: 'machine-name', status: 'NEW' },
      { id: 2, sourceId: 2, ip: '192.168.0.2', name: 'machine-name2', status: 'READY' },
      { id: 3, sourceId: 3, ip: '192.168.0.3', name: 'machine-name3', status: 'DISCONNECT' },
      { id: 4, sourceId: 2, ip: '192.168.0.4', name: 'machine-name4', status: 'INITIALIZING' },
      { id: 5, sourceId: 2, ip: '192.168.0.5', name: 'machine-name5', status: 'INIT_FAILED' }
    ],
    total: 45
  });
});

app.post('/api/machines', (req, res) => {
  setTimeout(() => {
    res.send('');
  }, 1000);
});

const machineSources = [
  { id: 1, name: '阿里云', masterUrls: 'http://127.0.0.1:8080,http://127.0.0.2' },
  { id: 2, name: '海尔青岛', masterUrls: 'http://127.0.0.3', companyId: 2, companyName: '端点科技' }
];

app.get('/api/machine-sources/all', (req, res) => {
  res.send(machineSources);
});

app.post('/api/machine-sources', (req, res) => {
  setTimeout(() => {
    machineSources.push({ id: 3, name: 'AWS', masterUrls: '走你' });
    res.send('');
  }, 2000);
});

app.post('/api/machine-sources/:id/update', (req, res) => {
  setTimeout(() => {
    res.send('');
  }, 2000);
});

app.get('/api/companies/search', (req, res) => {
  res.send({
    list: [
      { id: 1, name: '端点科技', logo: 'http://git.terminus.io/terminus/Beedrill/avatar', desc: '牛逼公司', type: 'BOTH' },
      { id: 2, name: '海尔', logo: 'http://git.terminus.io/terminus/Beedrill/avatar', desc: '海尔兄弟！', type: 'CUSTOMER' },
      { id: 3, name: '东软', logo: 'http://git.terminus.io/terminus/Beedrill/avatar', desc: 'X软X巨头', type: 'ISV' }
    ],
    total: 3
  });
});

app.post('/api/builders/build/:unitId', (req, res) => {
  setTimeout(() => {
    const lastBuild = {
      unitId: 1,
      uuid: '3345-5432-11234',
      createdAt: 1318781876406,
      updatedAt: 1318781876406,
      image: 'wtf/3345-5432-11234',
      status: 'BUILDING'
    };
    units[1].lastBuild = lastBuild;
    units[1].children.forEach(unit => { unit.lastBuild = lastBuild; });
    setTimeout(() => {
      lastBuild.status = 'COMPLETED';
    }, 10000);
    res.send('3345-5432-11234');
  }, 1000);
});

app.get('/api/builders/:uuid/log', (req, res) => {
  res.send({
    content: '33455432\n',
    status: 1
  });
});

app.post('/api/images/upload', (req, res) => {
  res.send({
    url: 'http://git.terminus.io/terminus/Beedrill/avatar'
  });
});

app.all('/api/*', (req, res) => {
  console.log(`not matched request: ${req.path}, proxy to back server`);
  proxy.web(req, res);
});

app.get('*', (req, res) => {
  console.log(`request path: ${req.path}`);
  res.sendFile(`${__dirname}/public/index.html`);
});

app.listen(port);
console.log(`listening at port ${port}`);
